﻿using Pay.Core;
using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Pay.Distribution.Controllers {
    public class LogisticsController : GeneralController {
        private ILogisticsService _ilogisticsService;
        private ILogisticsDetailsService _logisticsDetailsService;
        private IOrderService _orderService;
        private IPayInfoService _payInfoService;
        private ILogisticsListService _logisticsListService;
        private IMerchantService _iMerchantService;
        
        public LogisticsController(ILogisticsService ilogisticsService, ILogisticsListService logisticsListService, ILogisticsDetailsService logisticsDetailsService, IOrderService orderService,IPayInfoService payInfoService, IMerchantService iMerchantService) {
            _ilogisticsService = ilogisticsService;
            _logisticsDetailsService = logisticsDetailsService;
            _orderService = orderService;
            _payInfoService = payInfoService;
            _logisticsListService = logisticsListService;
            _iMerchantService = iMerchantService;
        }
        /// <summary>
        /// 填写提单号
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public JsonResult FillSingle(string Ids) {
            var paylist = new List<pay_info_dto>();
            if (Ids != "") {
                var arry = Ids.TrimEnd(',').Split(',');
                if (arry.Length > 0) {
                    foreach (var Id in arry) {
                        var model = _payInfoService.GetPayById(Convert.ToInt64(Id));
                        paylist.Add(model);
                    }
                }
            }
            return Json(ResultToJson.Json(paylist), JsonRequestBehavior.AllowGet);
        }
        public JsonResult del(long Id) {
            ApiResultMessage api = new ApiResultMessage();
            var result=  _payInfoService.Update(Id, 0, 2);
            if (result >= 0) {
                api.result_code = 1000;
            } else {
                api.result_code = -1;
            }
            return Json(ResultToJson.Json(api), JsonRequestBehavior.AllowGet);
        }
        public JsonResult FillSplitPlate(string Ids) {
            var paylist = new List<pay_info_dto>();
            if (Ids != "") {
                var arry = Ids.TrimEnd(',').Split(',');
                if (arry.Length > 0) {
                    foreach (var Id in arry) {
                        var model = _payInfoService.GetPayById(Convert.ToInt64(Id));
                        paylist.Add(model);
                    }
                }
            }
            return Json(ResultToJson.Json(paylist), JsonRequestBehavior.AllowGet);
        }
        public JsonResult Add(string Ids,string logid) {
            ApiResultMessage api = new ApiResultMessage();
            var result = -1;
            if (logid != "") {
                if (Ids != "") {
                    var arry = Ids.TrimEnd(',').Split(',');
                    if (arry.Length > 0) {
                        foreach (var Id in arry) {
                            var model = _payInfoService.GetPayById(Convert.ToInt64(Id));
                            model.boardid = Convert.ToInt64(logid);
                            result = _payInfoService.Update(Convert.ToInt64(Id), Convert.ToInt64(logid), 2);

                        }
                       
                        if (result >= 0) {
                            api.result_code = 1000;
                            api.result_msg = "操作成功";

                        } else {
                            api.result_code = -1;
                            api.result_msg = "系统异常";
                        }
                    }
                } else {
                    api.result_code = -1;
                    api.result_msg = "系统异常";
                }
            } else {
                api.result_code = -1;
                api.result_msg = "系统异常";
            }
            return Json(ResultToJson.Json(api), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存提单信息
        /// </summary>
        /// <param name="boardname"></param>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public JsonResult SaveBoard(string boardname, string Ids) {
            ApiResultMessage api = new ApiResultMessage();
            var model = new logistics_list_dto();
            model.board_name = boardname;
            model.payinfoids = Ids;
            model.create_time = DateTime.Now;
            model.type = 2;
            model.statuss = LogisticsStatuss.BillLading;
            model.board_no= DtoHelper.GenerateOrderNumber();
            var LogistListId = _logisticsListService.Add(model);
            if (LogistListId >= 0) {
                var arry = Ids.TrimEnd(',').Split(',');
                if (arry.Length > 0) {
                    foreach (var id in arry) {
                        _payInfoService.Update(Convert.ToInt64(id), LogistListId, 2);
                    }
                }
                var LogisticsDetails = new logistics_details_dto();
                LogisticsDetails.logisticsid = LogistListId;
                LogisticsDetails.logisticsstatus = LogisticsStatuss.BillLading;
                LogisticsDetails.logisticstime = DateTime.Now;
                LogisticsDetails.manageid = currentUser.user_id;
                _logisticsDetailsService.Add(LogisticsDetails);
                api.result_msg = "操作成功";
                api.result_code = 1000;
            } else {
                api.result_msg = "系统异常";
                api.result_code = -1;

            }
            return Json(ResultToJson.Json(api), JsonRequestBehavior.AllowGet);
        }
        public JsonResult SplitPlateList(LogiticsQuery query) {
            query.Type = 1;
            var list = _logisticsListService.Gets(query);
            return Json(ResultToJson.Json(list), JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 保存板信息
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="boardname"></param>
        /// <param name="length"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public JsonResult SavePlate(long Id, string boardname, string length, string width, string height, string Ids) {
            ApiResultMessage api = new ApiResultMessage();
            var model = new logistics_list_dto();
            model.board_name = boardname;
            model.board_no= DtoHelper.GenerateOrderNumber();
            model.create_time = DateTime.Now;
            if (length == "") {
                model.length = 0;
            } else {
                model.length = Convert.ToDouble(length);
            }
            if (width == "") {
                model.width = 0;
            } else {
                model.width = Convert.ToDouble(width);
            }
            if (height == "") {
                model.high = 0;
            } else {
                model.high = Convert.ToDouble(height);
            }
            model.statuss = LogisticsStatuss.SplitPlate;
            model.parentid = Id;
            model.type = 1;
            model.payinfoids = Ids;
           var plateid= _logisticsListService.Add(model);
            if (plateid > 0) {
                var arry = Ids.TrimEnd(',').Split(',');
                if (arry.Length > 0) {
                    foreach (var id in arry) {
                        _payInfoService.Update(Convert.ToInt64(id), plateid, 1);
                    }
                }

                var LogisticsDetails = new logistics_details_dto();
                LogisticsDetails.logisticsid = Id;
                LogisticsDetails.logisticsstatus = LogisticsStatuss.SplitPlate;
                LogisticsDetails.logisticstime = DateTime.Now;
                LogisticsDetails.manageid = currentUser.user_id;
                _logisticsDetailsService.Add(LogisticsDetails);
                api.result_msg = "操作成功";
                api.result_code = 1000;
            } else {
                api.result_msg = "系统异常";
                api.result_code = -1;
            }
            return Json(ResultToJson.Json(api), JsonRequestBehavior.AllowGet);
        }
        public ActionResult Index() {
            return View();
        }
        public JsonResult FinishDeclare(long id) {
            var list = _payInfoService.GetListByPlateId(id);
            var orderlist = new List<order_dto>();
            if (list != null && list.Count > 0) {
                foreach (var item in list) {
                    var temp = _orderService.GetListByPayId(item.id);
                    orderlist.AddRange(temp);
                }
            }
            return Json(ResultToJson.Json(orderlist), JsonRequestBehavior.AllowGet);
        }
        public JsonResult StartFlight(long id) {
            var model = _logisticsListService.GetById(id);
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }
        public JsonResult SaveNO(logistics_dto model) {
            ApiResultMessage api = new ApiResultMessage();
            var Model = _logisticsListService.GetById(model.id);
            Model.flightno = model.flightno;
            Model.postalno = model.postalno;
            Model.statuss = LogisticsStatuss.FinishFlight;
            if (_logisticsListService.Update(Model, currentUser.user_id) > 0) {
                api.result_msg = "操作成功";
                api.result_code = 1000;

            } else {
                api.result_code = -1;
                api.result_msg = "系统异常";
            }
            return Json(ResultToJson.Json(api), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 保存毛重和法定重量
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public JsonResult Save(List<order_dto> list) {
            ApiResultMessage api = new ApiResultMessage();
            if (list != null && list.Count > 0) {
                foreach (var item in list) {
                    if (_orderService.UpdateOrderItem(item.id, item.order_items) > 0) {
                        var model = _logisticsListService.GetLogisticsList(item.pay_id);
                        if (model != null) {
                            model.statuss = LogisticsStatuss.AirmailFlight;
                            if (_logisticsListService.Update(model, currentUser.user_id) >= 0) {
                                api.result_msg = "操作成功";
                                api.result_code = 1000;
                            } else {

                                api.result_code = -1;
                                api.result_msg = "系统异常";
                            }

                        } else {
                            api.result_code = -1;
                            api.result_msg = "系统异常";
                        }
                    }
                }
            } else {
                api.result_code = -1;
                api.result_msg = "系统异常";
            }

            return Json(ResultToJson.Json(api), JsonRequestBehavior.AllowGet);
        }
        public JsonResult Post(int id) {
            var msg = _ilogisticsService.Post(id, currentUser.user_id);
            var model = new ApiResultMessage();

            if (msg == "受理成功") {
                model.result_code = 1000;

            } else {
                model.result_code = 100;
            }
            model.result_msg = msg;
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetList(long id) {
            var payinfo = _payInfoService.GetListByPlateId(id);
            var logistic = _logisticsListService.GetLogisticByPlateId(id);
            var logistic_detail = _logisticsDetailsService.GetLogisticsDeteil(logistic);
            var model = _logisticsDetailsService.GetList(payinfo[0].orders[0]);
            trace trace = new trace();
            logistic_results_ex result = new logistic_results_ex() {
                ebusiness_id = model.EBusinessID,
                shipper_code = model.ShipperCode,
                logistic_code = model.LogisticCode,
                traces = new List<trace>()
            };
            foreach (var item in model.Traces) {
                //logistic_detail[0].logisticsstatus = EnumExtensions.ToDescription(item.logisticsstatus);
                foreach (var detail in logistic_detail) {
                    if (item.AcceptStation == EnumExtensions.ToDescription(detail.logisticsstatus)) {
                        var temp = logistic.Where(c => c.id == detail.logisticsid).First();
                        trace.board_no = temp.board_no;
                        trace.board_name = temp.board_name;
                        trace.accept_station = item.AcceptStation;
                        trace.accept_time = item.AcceptTime;
                        trace.manage_name = detail.manage.name;
                        result.traces.Add(trace);
                        trace = new trace();
                    }
                }
            }
            return Json(ResultToJson.Json(result), JsonRequestBehavior.AllowGet);
        }
        public JsonResult tidan(long id) {
         
            var list = _payInfoService.GetListByBoardId(id);
            return Json(ResultToJson.Json(list), JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 获取物流列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public JsonResult Gets(LogiticsQuery query) {
            query.Type = 2;

            var model = _logisticsListService.Gets(query);
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 分板
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult SplitPlate(long Id) {
            var query = new PayInfoQuery();
            query.boardid = Id;
            var list = _payInfoService.Get(query);
            return Json(ResultToJson.Json(list), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Get(long id) {
            //var model = _ilogisticsService.Get(id);
            //return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
            return null;
        }
        /// <summary>
        /// 修改物流状态 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public JsonResult Update(long id, int status) {
            ApiResultMessage api = new ApiResultMessage();
            var model = _logisticsListService.GetById(id);
            if (model != null) {

                model.statuss = (LogisticsStatuss)status;
                if (_logisticsListService.Update(model, currentUser.user_id) >= 0) {

                    api.result_code = 1000;
                    api.result_msg = "修改成功";

                } else {
                    api.result_code = -1;
                    api.result_msg = "系统异常";
                }
            } else {
                api.result_code = -1;
                api.result_msg = "系统异常";
            }
            return Json(ResultToJson.Json(api), JsonRequestBehavior.AllowGet);
        }
        public JsonResult PayList() {
            var query = new PayInfoQuery();
            //query.size = 10;
            //query.merchant_id = currentUser.user_id;
            var list = _payInfoService.Get(query);
            List<pay_info_dto> pay_infos= new List<pay_info_dto>();
            foreach (var pay_info in list) {
                foreach (var order in pay_info.orders) {
                    if (order.status == OrderStatus.Confirm)
                        pay_infos.Add(pay_info);
                }
            }
            return Json(ResultToJson.Json(pay_infos), JsonRequestBehavior.AllowGet);
        }

    }
}